package cn.netswap.crate.handler;

import cn.netswap.crate.annotation.Table;
import cn.netswap.crate.datasource.CrateHikariDataSource;
import cn.netswap.crate.exception.CrateDbTableEmptyException;
import cn.netswap.crate.repository.CrudRepository;
import cn.netswap.crate.util.AutoCrateTableSqlUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;


public class CrateDbAutoCrateTableHandler implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
            ApplicationContext context = event.getApplicationContext();
            Map<String, CrudRepository> allClazz = context.getBeansOfType(CrudRepository.class);
            for (String c : allClazz.keySet()) {
                Type type = allClazz.get(c).getClass().getGenericSuperclass();
                if (type instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) type;
                    try {
                        String className = parameterizedType.getActualTypeArguments()[0].getTypeName();
                        Class<?> clazz = Class.forName(className);
                        if (!StringUtils.isEmpty(AnnotationUtils.findAnnotation(clazz, Table.class))) {
                            String sql = AutoCrateTableSqlUtil.generateTableSql(clazz);
                            CrateHikariDataSource hikari = context.getBean("crateHikariDataSource", CrateHikariDataSource.class);
                            Connection connectoin = hikari.getDataSource().getConnection();
                            ResultSet resultSet = connectoin.createStatement().executeQuery("select 1");
                            while (resultSet.next()){
                                System.out.println("rs == "+resultSet.getInt(1));
                            }
                            connectoin.close();
                        }
                    } catch (ClassNotFoundException | CrateDbTableEmptyException | SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
    }
}